<?php

namespace app\service;

use app\model\CarQrcode;
use app\model\User;
use library\wechat;
use Tinywan\Jwt\JwtToken;
use app\enum\UserCode;

class UserService extends Base
{
    //登录
    public function toLoginByCode($code, $platform, $nickname, $avatar): array
    {
        //获取微信小程序的openid
        switch ($platform) {
            case UserCode::PLATFORM['测试']:
                $openid = $code;
                break;
            case UserCode::PLATFORM['微信']:
                $openid = (new wechat())->get_openid($code);
                break;
            default:
                return apiError('平台错误');
        }
        //查询会员信息
        $user = User::where(['openid' => $openid])->find();
        if (empty($user)) {
            //注册
            $param = [
                'openid' => $openid,
                'nickname' => $nickname,
                'avatar' => $avatar,
                'platform' => $platform,
                //'join_ip' => request()->getRemoteIp(),
                'join_time' => date('Y-m-d H:i:s'),
                'status' => UserCode::STATUS_NORMAL,
            ];

            //注册成功
            $user = new User();
            $user->save($param);
        }
        if ($user['status'] == UserCode::STATUS_DISABLE) {
            return apiError('该账号已停用');
        }
        $user->save();

        $extend = [
            'id' => $user['id'],
            'name' => '',
            'access_exp' => 864000000,  // 100天
            'refresh_exp' => 864000000,  // 100天
            'client' => JwtToken::TOKEN_CLIENT_MOBILE
        ];
        $generateToken = JwtToken::generateToken($extend);

        if ($generateToken) {
            $data = ['token' => $generateToken['access_token'], 'user_info' => self::info($user)];
            return apiSuccess($data);
        }
        return apiError('失败');

    }

    public static function info(User $user)
    {
        return User::where(['id' => $user->id])->find();
    }




}